package main

import (
	"auto/src/set_config"
	"auto/src/put_bot"
	"fmt"
	"log"
	"os"
	"regexp"     // 用于正则表达式处理
	"os/exec"
	//"path/filepath"
	//"time"
	"io"
	"bytes"
	"github.com/lxn/walk"
	. "github.com/lxn/walk/declarative"
	"gopkg.in/yaml.v2"
	"github.com/axgle/mahonia"
)

// 使用你已有的 Config 结构体
type ConfigWindow struct {
    *walk.MainWindow
    config *set_config.Config
    
    // 数据配置控件
    rootPathEdit     *walk.LineEdit
    excelPythonEdit  *walk.LineEdit
    picPythonEdit    *walk.LineEdit
    fileNameEdit     *walk.LineEdit
    robotWebhookEdit *walk.LineEdit
    fileWebhookEdit  *walk.LineEdit
    
    // MySQL 配置控件
    mysqlHostEdit     *walk.LineEdit
    mysqlPortEdit     *walk.LineEdit
    mysqlDBnameEdit   *walk.LineEdit
    mysqlUsernameEdit *walk.LineEdit
    mysqlPasswordEdit *walk.LineEdit
    
    // Python 配置控件
    pythonRootPathEdit *walk.LineEdit
    pythonFileNameEdit *walk.LineEdit
    pythonRangeEdit    *walk.LineEdit
    
    // 输出和控制控件
    outputTextEdit *walk.TextEdit
    runBtn         *walk.PushButton
    clearBtn       *walk.PushButton
    saveBtn        *walk.PushButton
    loadBtn        *walk.PushButton
}


func main() {
	//加载配置文件
    mw := &ConfigWindow{
		config: &set_config.Config{},
    }
    // 加载现有配置或设置默认值
	mw.loadOrInitConfig()
	//调试
	println(mw.config.Data.Excel_Python)
    if _, err := (MainWindow{
        AssignTo: &mw.MainWindow,
        Title:    "量子密信自动化助手",
        //Icon: "favicon.ico",
        MinSize:  Size{Width: 800,Height: 600},
        Size:     Size{Width:1000,Height:700},
        Layout:   VBox{},
        Children: []Widget{
            mw.createTabWidget(),
            mw.createOutputGroup(),
            mw.createControlButtons(),
        },
    }).Run(); err != nil {
        log.Fatal(err)
    }
}

func (mw *ConfigWindow) loadOrInitConfig() {
    // 尝试加载现有配置
    config := set_config.Load_Config(".")
    mw.config = config
	mw.updateUIFromConfig()
}

func (mw *ConfigWindow) createTabWidget() Widget {
    return TabWidget{
        Pages: []TabPage{
            {
                Title:  "数据配置",
                Layout: Grid{Columns: 2, Spacing: 10, Margins: Margins{10, 10, 10, 10}},
                Children: mw.createDataConfigControls(),
            },
            {
                Title:  "MySQL配置",
                Layout: Grid{Columns: 2, Spacing: 10, Margins: Margins{10, 10, 10, 10}},
                Children: mw.createMySQLConfigControls(),
            },
            {
                Title:  "Python配置",
                Layout: Grid{Columns: 2, Spacing: 10, Margins: Margins{10, 10, 10, 10}},
                Children: mw.createPythonConfigControls(),
            },
        },
    }
}

func (mw *ConfigWindow) createDataConfigControls() []Widget {
    return []Widget{
        Label{Text: "根目录:"},
        Composite{
            Layout: HBox{MarginsZero: true},
            Children: []Widget{
                LineEdit{
                    AssignTo: &mw.rootPathEdit,
                    Text:     mw.config.Data.RootPath,
                    OnTextChanged: func() {
                        mw.config.Data.RootPath = mw.rootPathEdit.Text()
                    },
                },
                PushButton{
                    Text: "选择",
                    OnClicked: func() {
                        mw.selectFolder(&mw.rootPathEdit, "选择根目录")
                    },
                },
            },
        },
        
        Label{Text: "Excel Python脚本:"},
        Composite{
            Layout: HBox{MarginsZero: true},
            Children: []Widget{
                LineEdit{
                    AssignTo: &mw.excelPythonEdit,
                    Text:     mw.config.Data.Excel_Python,
                    OnTextChanged: func() {
                        mw.config.Data.Excel_Python = mw.excelPythonEdit.Text()
                    },
                },
                PushButton{
                    Text: "选择",
                    OnClicked: func() {
                        mw.selectFile(&mw.excelPythonEdit, "选择Excel生成脚本", "Python文件 (*.py)|*.py")
                    },
                },
            },
        },
        
        Label{Text: "图片 Python脚本:"},
        Composite{
            Layout: HBox{MarginsZero: true},
            Children: []Widget{
                LineEdit{
                    AssignTo: &mw.picPythonEdit,
                    Text:     mw.config.Data.Pic_Python,
                    OnTextChanged: func() {
                        mw.config.Data.Pic_Python = mw.picPythonEdit.Text()
                    },
                },
                PushButton{
                    Text: "选择",
                    OnClicked: func() {
                        mw.selectFile(&mw.picPythonEdit, "选择图片生成脚本", "Python文件 (*.py)|*.py")
                    },
                },
            },
        },
        
        Label{Text: "文件名:"},
        LineEdit{
            AssignTo: &mw.fileNameEdit,
            Text:     mw.config.Data.FileName,
            OnTextChanged: func() {
                mw.config.Data.FileName = mw.fileNameEdit.Text()
            },
        },
        
        Label{Text: "机器人Webhook:"},
        LineEdit{
            AssignTo: &mw.robotWebhookEdit,
            Text:     mw.config.Data.Robot_Webhook,
            OnTextChanged: func() {
                mw.config.Data.Robot_Webhook = mw.robotWebhookEdit.Text()
            },
        },
        
        Label{Text: "文件上传Webhook:"},
        LineEdit{
            AssignTo: &mw.fileWebhookEdit,
            Text:     mw.config.Data.File_Webhook,
            OnTextChanged: func() {
                mw.config.Data.File_Webhook = mw.fileWebhookEdit.Text()
            },
        },
    }
}

func (mw *ConfigWindow) createMySQLConfigControls() []Widget {
    portText := fmt.Sprintf("%d", mw.config.Mysql.Port)
    if mw.config.Mysql.Port == 0 {
        portText = ""
    }
    
    return []Widget{
        Label{Text: "数据库地址:"},
        LineEdit{
            AssignTo: &mw.mysqlHostEdit,
            Text:     mw.config.Mysql.Host,
            OnTextChanged: func() {
                mw.config.Mysql.Host = mw.mysqlHostEdit.Text()
            },
        },
        
        Label{Text: "端口:"},
        LineEdit{
            AssignTo: &mw.mysqlPortEdit,
            Text:     portText,
            OnTextChanged: func() {
                var port int
                fmt.Sscanf(mw.mysqlPortEdit.Text(), "%d", &port)
                mw.config.Mysql.Port = port
            },
        },
        
        Label{Text: "数据库名:"},
        LineEdit{
            AssignTo: &mw.mysqlDBnameEdit,
            Text:     mw.config.Mysql.DBname,
            OnTextChanged: func() {
                mw.config.Mysql.DBname = mw.mysqlDBnameEdit.Text()
            },
        },
        
        Label{Text: "用户名:"},
        LineEdit{
            AssignTo: &mw.mysqlUsernameEdit,
            Text:     mw.config.Mysql.Username,
            OnTextChanged: func() {
                mw.config.Mysql.Username = mw.mysqlUsernameEdit.Text()
            },
        },
        
        Label{Text: "密码:"},
        LineEdit{
            AssignTo: &mw.mysqlPasswordEdit,
            Text:       mw.config.Mysql.Password,
            PasswordMode: true,
            OnTextChanged: func() {
                mw.config.Mysql.Password = mw.mysqlPasswordEdit.Text()
            },
        },
    }
}

func (mw *ConfigWindow) createPythonConfigControls() []Widget {
    return []Widget{
        Label{Text: "Python根目录:"},
        Composite{
            Layout: HBox{MarginsZero: true},
            Children: []Widget{
                LineEdit{
                    AssignTo: &mw.pythonRootPathEdit,
                    Text:     mw.config.Python.RootPath,
                    OnTextChanged: func() {
                        mw.config.Python.RootPath = mw.pythonRootPathEdit.Text()
                    },
                },
                PushButton{
                    Text: "选择",
                    OnClicked: func() {
                        mw.selectFolder(&mw.pythonRootPathEdit, "选择Python根目录")
                    },
                },
            },
        },
        
        Label{Text: "文件名:"},
        LineEdit{
            AssignTo: &mw.pythonFileNameEdit,
            Text:     mw.config.Python.FileName,
            OnTextChanged: func() {
                mw.config.Python.FileName = mw.pythonFileNameEdit.Text()
            },
        },
        
        Label{Text: "范围:"},
        LineEdit{
            AssignTo: &mw.pythonRangeEdit,
            Text:     mw.config.Python.Range,
            OnTextChanged: func() {
                mw.config.Python.Range = mw.pythonRangeEdit.Text()
            },
        },
    }
}

func (mw *ConfigWindow) createOutputGroup() Widget {
    return GroupBox{
        Title:  "模拟CMD输出",
        Layout: VBox{},
        Children: []Widget{
            TextEdit{
                AssignTo: &mw.outputTextEdit,
                ReadOnly: true,
                VScroll:  true,
                HScroll:  true,  // 添加水平滚动条
                MinSize:  Size{Width: 0, Height: 300},
                Font:     Font{Family: "Consolas", PointSize: 10},
                Text:     "", // 初始化为空
            },
        },
    }
}

func (mw *ConfigWindow) createControlButtons() Widget {
    return Composite{
        Layout: HBox{},
        Children: []Widget{
            PushButton{
                AssignTo: &mw.runBtn,
                Text:     "运行模拟",
                OnClicked: mw.runSimulation,
            },
            PushButton{
                AssignTo: &mw.clearBtn,
                Text:     "清空输出",
                OnClicked: func() {
                    mw.outputTextEdit.SetText("")
                },
            },
            PushButton{
                AssignTo: &mw.saveBtn,
                Text:     "保存配置",
                OnClicked: mw.saveConfig,
            },
            PushButton{
                AssignTo: &mw.loadBtn,
                Text:     "加载配置",
                OnClicked: mw.loadConfig,
            },
        },
    }
}

func (mw *ConfigWindow) selectFolder(edit **walk.LineEdit, title string) {
    dlg := new(walk.FileDialog)
    dlg.Title = title
    
    if ok, err := dlg.ShowBrowseFolder(mw); err != nil {
        mw.appendOutput("错误: " + err.Error() + "\n")
    } else if ok {
        (*edit).SetText(dlg.FilePath)
    }
}

func (mw *ConfigWindow) selectFile(edit **walk.LineEdit, title string, filter string) {
    dlg := new(walk.FileDialog)
    dlg.Title = title
    dlg.Filter = filter
    
    if ok, err := dlg.ShowOpen(mw); err != nil {
        mw.appendOutput("错误: " + err.Error() + "\n")
    } else if ok {
        (*edit).SetText(dlg.FilePath)
    }
}


//输出框
func (mw *ConfigWindow) appendOutput(text string) {
    currentText := mw.outputTextEdit.Text()
    newText := currentText + text + "\r\n"  // 确保每次输出都换行
    mw.outputTextEdit.SetText(newText)
    // 滚动到底部
    textLength := len(newText)
    mw.outputTextEdit.SetTextSelection(textLength, 0)
}

//点击运行
func (mw *ConfigWindow) runSimulation() {
    mw.runBtn.SetEnabled(false)
    defer mw.runBtn.SetEnabled(true)
    walk.MsgBox(mw, "配置提醒", "请确定已经正确保存配置，本运行只作测试，配置成功后使用终端自动运行版本即可！\n 请确保excel_to_img.py包依赖已经安装且正确运行，点击确定继续运行", walk.MsgBoxIconWarning)
    mw.appendOutput("================== 开始运行 ==================")
    // 捕获标准输出
    oldStdout := os.Stdout
    r, w, _ := os.Pipe()
    os.Stdout = w
    
    var out bytes.Buffer
	execPythonPath := mw.config.Data.RootPath + mw.config.Data.Excel_Python //python的绝对路径
	cmd := exec.Command("python", execPythonPath) // 执行Python脚本
	cmd.Stdout = &out // 创建缓冲区获取输出
	cmd.Stderr = &out // 将错误输出也重定向到缓冲区
	if err := cmd.Run(); err != nil { 
		println("newGen erro:", err.Error())
		println("Python输出:", out.String()) // 新增，打印详细错误
		return
	}
	 // 将 GBK 编码转换为 UTF-8
    decoder := mahonia.NewDecoder("gbk")
    fullOutput := decoder.ConvertString(out.String())
	fmt.Printf("完整输出:%s\r\n", fullOutput)
	// 使用正则表达式匹配目标消息
	re := regexp.MustCompile(`@所有人.*?请各分公司进行高效整治`)
	message := re.FindString(fullOutput)
	if message != "" {
		//fmt.Printf("提取的消息:%", message)
		// 使用 match 进行后续处理
	} else {
		println("未找到目标消息")
	}
	fmt.Printf("正在准备图片...\r\n")
	// 生成图片 
	picPythonPath := mw.config.Data.RootPath + mw.config.Data.Pic_Python
	cmd = exec.Command("python", picPythonPath,				
					"-p", mw.config.Python.RootPath,
					"-f", mw.config.Python.FileName,
					"-r", mw.config.Python.Range)
	_ = cmd.Run()
	fmt.Printf("excel更新成功...\r\n")
	// 准备发送
	put_bot.Step(message,mw.config.Data.FileName ,mw.config) //传入参数需要发送的消息参数
    
    // 恢复标准输出并读取内容
    w.Close()
    os.Stdout = oldStdout
    
    var buf bytes.Buffer
    io.Copy(&buf, r)
    
    // 在模拟CMD中显示捕获的输出
    capturedOutput := buf.String()
    if capturedOutput != "" {
        mw.appendOutput(capturedOutput)
    }
    mw.appendOutput("✓ 执行完成")
}

//保存配置文件
func (mw *ConfigWindow) saveConfig() {
    dlg := new(walk.FileDialog)
    dlg.Title = "保存配置文件"
    dlg.Filter = "YAML文件 (*.yaml)|*.yaml|所有文件 (*.*)|*.*"
    
    if ok, err := dlg.ShowSave(mw); err != nil {
        mw.appendOutput("保存配置错误: " + err.Error() + "\n")
    } else if ok {
        data, err := yaml.Marshal(mw.config)
        if err != nil {
            mw.appendOutput("序列化配置错误: " + err.Error() + "\n")
            return
        }
        
        if err := os.WriteFile(dlg.FilePath, data, 0644); err != nil {
            mw.appendOutput("保存文件错误: " + err.Error() + "\n")
        } else {
            mw.appendOutput("配置已保存到: " + dlg.FilePath + "\n")
        }
    }
}

func (mw *ConfigWindow) loadConfig() {
    dlg := new(walk.FileDialog)
    dlg.Title = "加载配置文件"
    dlg.Filter = "YAML文件 (*.yaml;*.yml)|*.yaml;*.yml|所有文件 (*.*)|*.*"
    
    if ok, err := dlg.ShowOpen(mw); err != nil {
        mw.appendOutput("加载配置错误: " + err.Error() + "\n")
    } else if ok {
        data, err := os.ReadFile(dlg.FilePath)
        if err != nil {
            mw.appendOutput("读取文件错误: " + err.Error() + "\n")
            return
        }
        
        var config set_config.Config
        if err := yaml.Unmarshal(data, &config); err != nil {
            mw.appendOutput("解析YAML错误: " + err.Error() + "\n")
            return
        }
        
        mw.config = &config
        mw.updateUIFromConfig()
        mw.appendOutput("配置已从文件加载: " + dlg.FilePath + "\n")
    }
}

func (cw *ConfigWindow) updateUIFromConfig() {
    // 更新数据配置
    if cw.rootPathEdit != nil {
        cw.rootPathEdit.SetText(cw.config.Data.RootPath)
    }
    if cw.excelPythonEdit != nil {
        cw.excelPythonEdit.SetText(cw.config.Data.Excel_Python)
    }
    if cw.picPythonEdit != nil {
        cw.picPythonEdit.SetText(cw.config.Data.Pic_Python)
    }
    if cw.fileNameEdit != nil {
        cw.fileNameEdit.SetText(cw.config.Data.FileName)
    }
    if cw.robotWebhookEdit != nil {
        cw.robotWebhookEdit.SetText(cw.config.Data.Robot_Webhook)
    }
    if cw.fileWebhookEdit != nil {
        cw.fileWebhookEdit.SetText(cw.config.Data.File_Webhook)
    }
    
    // 更新MySQL配置
    if cw.mysqlHostEdit != nil {
        cw.mysqlHostEdit.SetText(cw.config.Mysql.Host)
    }
    if cw.mysqlPortEdit != nil {
        if cw.config.Mysql.Port > 0 {
            cw.mysqlPortEdit.SetText(fmt.Sprintf("%d", cw.config.Mysql.Port))
        } else {
            cw.mysqlPortEdit.SetText("")
        }
    }
    if cw.mysqlDBnameEdit != nil {
        cw.mysqlDBnameEdit.SetText(cw.config.Mysql.DBname)
    }
    if cw.mysqlUsernameEdit != nil {
        cw.mysqlUsernameEdit.SetText(cw.config.Mysql.Username)
    }
    if cw.mysqlPasswordEdit != nil {
        cw.mysqlPasswordEdit.SetText(cw.config.Mysql.Password)
    }
    
    // 更新Python配置
    if cw.pythonRootPathEdit != nil {
        cw.pythonRootPathEdit.SetText(cw.config.Python.RootPath)
    }
    if cw.pythonFileNameEdit != nil {
        cw.pythonFileNameEdit.SetText(cw.config.Python.FileName)
    }
    if cw.pythonRangeEdit != nil {
        cw.pythonRangeEdit.SetText(cw.config.Python.Range)
    }
}